<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }
}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}

//生成小程序二维码
function qrcode($value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
//        msg(-1, '', $response);
        return $response;
    } catch (\Exception $e) {
//        msg(-1, $e->getMessage(), '');
        return $e->getMessage();
    }
}

function showMsg($status, $message = '', $data = array())
{
    $result = array(
        'status' => $status,
        'message' => $message,
        'data' => $data
    );
    exit(json_encode($result));
}

function formatSizeUnits($bytes)
{
    if ($bytes >= 1073741824) {
        // 大于等于 1 GB
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        // 大于等于 1 MB
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        // 大于等于 1 KB
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } else {
        // 小于 1 KB
        $bytes = $bytes . ' Bytes';
    }
    return $bytes;
}

//1看视频 2兑换 3其他
function addFraction($memberId, $fraction_count = 2, $desc = ' ', $type = 1, $is_count = 1)
{
    $insert_data = array(
        'member_id' => $memberId,
        'create_time' => time(),
        'count' => $fraction_count,
        'desc' => $desc,
        'type' => $type,
        'is_count' => $is_count,
    );
    Db::name('fraction_record')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setInc('fraction', $fraction_count);
    } else {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setDec('fraction', $fraction_count);
    }
}

//获取优惠券
function getCoupons($memberId, $coupon_info, $get_type = 1, $invite_member_id = 0)
{
    $now_time = time();
    $insert_data = array(
        'member_id' => $memberId,
        'coupon_id' => $coupon_info['id'],
        'name' => $coupon_info['name'],
        'value' => $coupon_info['value'],
        'min_amount' => $coupon_info['min_amount'],
        'claimed_time' => $now_time,
        'start_time' => $now_time,
        'create_time' => time(),
        'get_type' => $get_type,
        'invite_member_id' => $invite_member_id,
        'desc' => $coupon_info['desc']
    );
    if ($coupon_info['effect_type'] == 1) {
        $insert_data['end_time'] = $coupon_info['effect_end'];
    } else {
        $insert_data['end_time'] = $now_time + ($coupon_info['effect_day'] * 86400);
    }
    //领取张数
    Db::name('coupons')
        ->where('id', '=', $coupon_info['id'])
        ->setInc('claimed_count');
    //增加会员优惠券
    $result_id = Db::name('member_coupons')->insertGetId($insert_data);
    return $result_id;
}

//订单回调
function orderPaySuccess($order_data)
{
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 2,
        'pay_time' => time(),
        'pay_status' => 1,
    );
    Db::startTrans();
    try {
        $linkage_info = Db::name('linkage')->find();
        $order_goods = Db::name('order_goods')->where([
            'order_id' => $order_data['id'],
            'goods_id' => $linkage_info['goods_id']
        ])->find();
        //判断是否有效分销订单
        if ($order_goods) {
            $order_update['is_effect_order'] = 1;
            Db::name('order_goods')->where([
                'order_id' => $order_data['id'],
                'goods_id' => $linkage_info['goods_id']
            ])->update([
                'is_effect_order' => 1
            ]);
        }
        $member_info = Db::name('member')->find($order_data['member_id']);
        if ($member_info['is_clock'] != 1) {
            Db::name('member')->update([
                'id' => $order_data['member_id'],
                'is_clock' => 1
            ]);
        }
        Db::name('order')->update($order_update);
        if ($order_data['mc_id']) {
            $mc_update = array(
                'id' => $order_data['mc_id'],
                'status' => 3,
            );
            Db::name('member_coupons')->update($mc_update);
        }
        Db::commit();
        return 1;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}

//todo 提现中
function finishOrder($order_info, $type = 1)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 4,
        'finish_time' => time(),
        'finish_type' => $type
    );
    Db::name('order')->update($update_data);
    //升级服务中心
    upServerCenter($order_info);
    //升级分公司
    upBrand($order_info);
    //复购返现
    //1推广奖2直推奖3间推奖4平级奖 5服务奖励6分公司奖励  7团队奖励 8提现 9普通推广 10服务中心复购11分公司复购12董事复购奖励
    reBuyReward($order_info);
    //普通返现
    returnMoney($order_info);
}

//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
//7已取消
function tuikuanServerOrder($order_info, $tui_moeny = 0.00, $is_houtui = 0)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny' => $tui_moeny
    );
    //优惠券
    if ($order_info['mc_id']) {
        Db::name('member_coupons')->update([
            'id' => $order_info['mc_id'],
            'status' => 1,
        ]);
    }
    //订单信息  order_after status 1待同意 2已同意 3已拒绝 4已发货 5已完成
    Db::name('order')->update($update_data);
    if ($is_houtui == 1) {
        $order_after = array(
            'tui_no' => 'cp' . GetOrderSN(2),
            'order_no' => $order_info['order_no'],
            'order_id' => $order_info['id'],
            'status' => 5,
            'create_time' => time(),
            'tui_reason' => '后台主动退款',
            'order_pay_money' => $order_info['pay_money'],
            'member_id' => $order_info['member_id'],
            'is_fa' => 0,
            'order_status' => 6,
            'tui_money' => $tui_moeny,
        );
        Db::name('order_after')->insertGetId($order_after);
    }
}

function getTopInviter($userId)
{
    while (true) {
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            return null; // 用户不存在
        }
        // 如果当前用户的 invite_id 为 0，说明是顶级用户
        if ($user['invite_id'] == 0) {
            return $user;
        }
        // 继续查找邀请人
        $userId = $user['invite_id'];
    }
}

//获取邀请
function getInvite($invite_id)
{
    //上级id 老板id 顶级id
    //invite_id boss_invite_id top_invite_id
    $return_data = array(
        'invite_id' => 0,
        'boss_invite_id' => -1,//老板不确定
        'top_invite_id' => 0
    );
    $member_info = Db::name('member')->where(['id' => $invite_id])->find();
    if (!$member_info) {
        return $return_data;
    }
    if ($member_info['level_id'] <= 1) {
        return $return_data;
    }
    $top_user = getTopInviter($invite_id);
    $return_data['top_invite_id'] = $top_user['id'];
    $return_data['invite_id'] = $invite_id;

//    if ($member_info['level_id']==2){
//        $return_data['boss_invite_id']=-1;//老板不确定
//    }

    if ($member_info['level_id'] > 2) {
        $return_data['boss_invite_id'] = $invite_id;
    }
    return $return_data;
}

//下单成功后找老板 输入用户id
function getBoss($member_id)
{
    $top = 1;
    while (true) {
        $member_info = Db::name('member')->where(['id' => $member_id])->find();
        if (!$member_info) {
            return 0;
        }
        $invite_member = Db::name('member')->where(['id' => $member_info['invite_id']])->find();
        if ($member_id == $member_info['invite_id']) {
            return 0;
        }
        if (!$invite_member) {
            return 0;
        }
        if ($invite_member['level_id'] >= 3 && $top == 1) {
            return $invite_member;
        }
        if ($invite_member['level_id'] >= 3 && $top > 1) {
            if (($invite_member['one_id'] == $member_id || $invite_member['tow_id'] == $member_id) && ($invite_member['invite_id'] == 0)) {
                return 0;
            }
            if ($invite_member['one_id'] != $member_id && $invite_member['tow_id'] != $member_id) {
                return $invite_member;
            }
        }
        $top++;
        $member_id = $invite_member['id'];
    }
}

//type 类型 1推广奖2直推奖3间推奖4平级奖5服务公司6分公司7团队奖励
function addMoney($member_id, $order_info, $type, $is_count, $money, $desc)
{
    $insert_data = array(
        'member_id' => $member_id,
        'is_count' => $is_count,
        'money' => $money,
        'type' => $type,
        'order_id' => $order_info['id'],
        'order_no' => $order_info['order_no'],
        'desc' => $desc,
        'create_time' => time()
    );
    if ($type == 7) {
        $insert_data['time'] = $lastMonthYear = date('Y', strtotime('-1 month'));
    }
    $insert_id = Db::name('member_finance')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')->where(['id' => $member_id])->setInc('money', $money);
    } else {
        Db::name('member')->where(['id' => $member_id])->setDec('money', $money);
    }
    return $insert_id;
}

//1推广奖2直推奖3间推奖4平级奖
//       reward  1推广奖2直推奖3间推奖4平级奖 5普通推广6服务中心复购7分公司复购8董事复购奖励
//member_finance 1推广奖2直推奖3间推奖4平级奖 5服务奖励6分公司奖励  7团队奖励 8提现 9普通推广 10服务中心复购11分公司复购12董事复购奖励
function reward($member_id, $order_info, $money, $type, $junior_member_id, $order_goods, $status = 0, $desc = '奖励', $ping_order_no = 0)
{
    if (!$order_info) {
        $order_info['id'] = 0;
        $order_info['order_no'] = 0;
    }
    if (!$order_goods) {
        $order_info['goods_id'] = 0;
        $order_info['num'] = 0;
    }
    $insert_data = array(
        'member_id' => $member_id,
        'money' => $money,
        'type' => $type,
        'order_id' => $order_info['id'],
        'order_no' => $order_info['order_no'],
        'junior_member_id' => $junior_member_id,
        'status' => $status,
        'goods_id' => $order_goods['goods_id'],
        'goods_num' => $order_goods['num'],
        'ping_order_no' => $ping_order_no,
        'create_time' => time(),
        'desc'=>$desc
    );
    $insert_id = Db::name('reward')->insertGetId($insert_data);
    if ($status) {
        addMoney($member_id, $order_info, $type, 1, $money, $desc);
    }
    return $insert_id;
}

//订单完成后普通返现 订单完成时后普通返利 goods_tui_money
function returnMoney($order_info)
{
    $member = Db::name('member')->find($order_info['member_id']);
    $invite_member = Db::name('member')->where([
        'id' => $member['invite_id']
    ])->find();
    if ($invite_member) {
        $order_goods_list = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->column('goods_id');

        $goods_tui_money = Db::name('goods_tui_money')->where([
            ['goods_id', 'in', $order_goods_list],
            ['level', '=', 1]
        ])->select();

        foreach ($goods_tui_money as $k => $v) {
            $order_goods = Db::name('order_goods')->where([
                'order_id' => $order_info['id'],
                'goods_id' => $v['goods_id']
            ])->find();
            $money = $order_goods['num'] * $v['money'];
            reward($invite_member['id'], $order_info, $money, 9, $order_info['member_id'], $order_goods, $status = 1, $desc = '普通推广', $ping_order_no = 0);
        }


    }
}

//输入id获取团队id 不包括本id
function getTeamMembersRecursive($userId)
{
    $teamMembers = [];
    // 查询当前用户直接邀请的用户
    $directMembers = Db::name('member')
        ->where('invite_id', $userId)
        ->column('id');

    // 将直接邀请的用户加入团队
    $teamMembers = array_merge($teamMembers, $directMembers);

    // 递归获取间接邀请的用户
    foreach ($directMembers as $memberId) {
        $teamMembers = array_merge($teamMembers, getTeamMembersRecursive($memberId));
    }
    return $teamMembers;
}

//输入id获取团队id 不包括本id 根据用户加入时间
function getTeamMembersRecursive_time($userId, $year, $month)
{
    $timeScope = getTimeScope($year . '-' . $month);
    $teamMembers = [];
    // 查询当前用户直接邀请的用户
    $directMembers = Db::name('member')
        ->where('invite_id', $userId)
        ->where('create_time', '<=', $timeScope['endTimestamp'])
        ->column('id');

    // 将直接邀请的用户加入团队
    $teamMembers = array_merge($teamMembers, $directMembers);

    // 递归获取间接邀请的用户
    foreach ($directMembers as $memberId) {
        $teamMembers = array_merge($teamMembers, getTeamMembersRecursive($memberId));
    }
    return $teamMembers;
}

//团队返回金额
function calculateTeamReward($amount)
{
    // 定义奖励规则
    $rewardRules = [
        10000 => 0.02,
        30000 => 0.03,
        50000 => 0.04,
        100000 => 0.05,
        300000 => 0.06,
        500000 => 0.068,
        700000 => 0.076,
        1000000 => 0.084,
        2000000 => 0.09,
        3000000 => 0.094,
        5000000 => 0.098,
        10000000 => 0.10
    ];
    // 如果业绩少于1万，返回0
    if ($amount < 10000) {
        return 0;
    }
    // 遍历奖励规则，找到对应的百分比
    $rewardPercentage = 0;
    foreach ($rewardRules as $threshold => $percentage) {
        if ($amount >= $threshold) {
            $rewardPercentage = $percentage;
        } else {
            break;
        }
    }

    // 计算奖励金额
    $rewardAmount = round($amount * $rewardPercentage, 2);
    return $rewardAmount;
}

//输入年月获取时间戳的范围
function getTimeScope($time)
{
    $startTimestamp = strtotime($time . '-01 00:00:00');
// 获取该月的最后一天的时间戳
    $endTimestamp = strtotime(date('Y-m-t 23:59:59', $startTimestamp));
    $data['startTimestamp'] = $startTimestamp;
    $data['endTimestamp'] = $endTimestamp;
    return $data;
}

function getEffectOrderMoney($member_ids, $startTimestamp, $endTimestamp)
{
    $money = 0;
    $effect_order_ids = Db::name('order')->where([
        ['member_id', 'in', $member_ids],
        ['status', 'in', [4, 5]],
        ['finish_time', 'between', [$startTimestamp, $endTimestamp]],
        ['is_effect_order', 'in', [1]],
    ])->column('id');
    if ($effect_order_ids) {
        $money = Db::name('order_goods')->where([
            ['order_id', 'in', $effect_order_ids],
            ['is_effect_order', '=', 1],
        ])->sum('sum_money');
    }
    return $money;
}

function teamMoney($year, $month, $member_id)
{
    $timeScope = getTimeScope($year . '-' . $month);
    //获取我的直属下级
    $junior_ids = Db::name('member')->where([
        'invite_id' => $member_id,
    ])->column('id');
    //本人的订单金额
    $money = getEffectOrderMoney($member_id, $timeScope['startTimestamp'], $timeScope['endTimestamp']);
    //遍历每个下级 获取下级的团队id 包含这个下级id
    //键值为下级id 团队金额 团队奖励
    $junior_team = array();
    foreach ($junior_ids as $k => $v) {
        $teamMembers = getTeamMembersRecursive($v);
        array_unshift($teamMembers, $v);//在团队中加入自己
        $team_money = getEffectOrderMoney($teamMembers, $timeScope['startTimestamp'], $timeScope['endTimestamp']);
        //获取$memberId 团队的所有订单金额
        $money += $team_money;
        $junior_team[$v]['team_ids'] = $teamMembers;
        $junior_team[$v]['order_money'] = $team_money;
        $junior_team[$v]['reward'] = calculateTeamReward($team_money);
    }
    $my_reward = calculateTeamReward($money);
    foreach ($junior_team as $k => $v) {
        $my_reward -= $v['reward'];
    }
    $return_date['junior_team'] = $junior_team;
    $return_date['money'] = $my_reward;
    $return_date['performance'] = $money;
    $return_date['team_num'] = count(getTeamMembersRecursive($member_id));
    return $return_date;
    //总结每个下级的团队的金额 以订单金额为基准（已经完成的订单） 并计算每个下级团队的奖励金额 增加所有团队的计算金额并计算本团队的奖励（包含自己的消费）
}

//用户是代理时 才会有推荐奖励 直接 间推 待收货的订单才行
function orderFinish($member_id, $order_info)
{
    $member_info = Db::name('member')->find($member_id);
    $up_member_info = Db::name('member')
        ->where(['id' => $member_info['invite_id']])
        ->find();
    $linkage_info = Db::name('linkage')->find();
    $order_goods = Db::name('order_goods')->where([
        'order_id' => $order_info['id'],
        'goods_id' => $linkage_info['goods_id']
    ])->find();
    //todo 上线关闭
    //1待支付 2待发货 3待收货 4已完成 5已评价
//        if ($order_info['status'] != 3) {
//            return -1;
//        }
    //判断是否有效订单
    if ($order_goods) {
        //判断当前用户是否代理或普通用户
        if ($member_info['level_id'] <= 2) {
            //判断是否重复购买
            if ($member_info['offect_order'] > 0) {
                //上级存在
                if ($up_member_info) {
                    finishOrder2($member_id, $member_info, $order_info, $up_member_info, $linkage_info, $order_goods, 2);
                }
            } else {
                //判断当前用户是否普通用户 是就升级
                if ($member_info['level_id'] == 1) {
                    $member_update = array(
                        'id' => $member_id,
                        'level_id' => 2
                    );
                    Db::name('member')->update($member_update);
                }
                //是否确定老板关系
                if ($member_info['boss_invite_id'] < 0) {
                    $boss_info = getBoss($member_id);
                    $member_update2['id'] = $member_id;
                    if ($boss_info) {
                        $member_update2['boss_invite_id'] = $boss_info['id'];
                    } else {
                        $member_update2['boss_invite_id'] = 0;
                    }
                    Db::name('member')->update($member_update2);
                    $member_info = Db::name('member')->find($member_id);
                }
                //用户有上级且存在
                if ($up_member_info) {
                    finishOrder2($member_id, $member_info, $order_info, $up_member_info, $linkage_info, $order_goods);
                }
            }
        }
        //增加有效订单
        Db::name('member')->where('id', '=', $member_id)->setInc('offect_order');
        //增加有效商品购买数量
        Db::name('member')->where('id', '=', $member_id)->setInc('offect_goods_num', $order_goods['num']);
    }
}

function finishOrder2($member_id, $member_info, $order_info, $up_member_info, $linkage_info, $order_goods, $type = 1)
{
    //老板就是上级且存在  1推广奖2直推奖3间推奖4平级奖
    if (($member_info['boss_invite_id'] == $member_info['invite_id']) && $member_info['boss_invite_id'] > 0) {
        //给老板直推奖
        $money = $order_goods['num'] * $linkage_info['zhi_money'];
        reward($member_info['boss_invite_id'], $order_info, $money, 2, $member_id, $order_goods, 1, '直推奖');
    }
    if ($member_info['boss_invite_id'] != $member_info['invite_id']) {
        if ($member_info['boss_invite_id'] > 0) {
            //给老板间推奖
            $money = $order_goods['num'] * $linkage_info['jin_money'];
            reward($member_info['boss_invite_id'], $order_info, $money, 3, $member_id, $order_goods, 1, '间推奖');
        }
        if ($up_member_info['level_id'] == 2) {
            //给上级推广奖
            $money = $order_goods['num'] * $linkage_info['gk_money'];
            reward($up_member_info['id'], $order_info, $money, 1, $member_id, $order_goods, 1, '推广奖');
            if ($type == 1) {
                //更改上级 推广两个进行升级
                if ($up_member_info['one_id'] > 0) {
                    $up_member_update = array(
                        'id' => $up_member_info['id'],
                        'tow_id' => $member_id,
                        'level_id' => 3
                    );
                } else {
                    $up_member_update = array(
                        'id' => $up_member_info['id'],
                        'one_id' => $member_id,
                    );
                }
                Db::name('member')->update($up_member_update);
            }
        }
    }
    if ($type == 1) {
        $invite_sort = Db::name('member')->where([
            ['invite_id', '=', $up_member_info['id']],
            ['invite_sort', '>', 0],
        ])->count();
        $member_update3['invite_sort'] = $invite_sort + 1;
        Db::name('member')->where(['id' => $member_id])->update($member_update3);
    }
}

//间隔天数
function getDaysDiff($send_time, $current_time = null)
{
    $current_time = $current_time ?? time();
    return abs(floor(($current_time - $send_time) / 86400));
}

//增加团队奖励
function sendTeamMoney($lastMonthYear, $member_id, $money, $performance, $team_num)
{
    $insert_data = array(
        'time' => $lastMonthYear,
        'member_id' => $member_id,
        'money' => $money,
        'performance' => $performance,
        'team_num' => $team_num,
        'create_time' => time()
    );
    $id = Db::name('team_money')->insertGetId($insert_data);
    return $id;
}

//获取商品优惠金额 通过个人身份
function getDiscountMoney($member_info, $goods_id)
{
    $cate_level_discount = Db::name('cate_level_discount')
        ->where([
            'goods_id' => $goods_id,
            'level_id' => $member_info['level_id']
        ])->find();
    if ($cate_level_discount) {
        return $cate_level_discount['money'];
    }
    return 0;
}

//==================================================================123=================================================
/**
 * 微信发货
 */
function WxSendOrderGoods($post, $token)
{


    $currentTime = new DateTime();

// 设置时区
    $currentTime->setTimezone(new DateTimeZone('UTC'));

// 将当前时间格式化为 RFC 3339 格式
    $rfc3339Time = $currentTime->format(DateTime::RFC3339);

    $use = SelectModelData('order', ['ordersn' => $post['ordersn']], 1);
    $user_token = $use['token'];
    $openid = SelectModelData('member', ['token' => $user_token], 1, 'openid');

    $config = [
        'app_id' => config('appid'),
        'mch_id' => config('mch_id'),
        'key' => config('paySecret'),
        'cert_path' => '', // XXX: 绝对路径！！！！
        'key_path' => '',      // XXX: 绝对路径！！！！
        'notify_url' => conf("lm", "url") . 'payres',
    ];

    $app = Factory::payment($config);

    $result = $app->order->queryByOutTradeNumber($post['ordersn']);

//    dump($result['transaction_id']);die;

    $str = "商品订单";

    $str_utf8 = mb_convert_encoding($str, "UTF-8", "auto");


    $sjrxx = GetAddress($use['address_id']);
    $iszt = intval($post['iszt']);
    if ($iszt == 1) {
        $arr = [
            'ordersn' => $post['ordersn'],
            'type' => 4,
//                'tracking_no'       =>$data['emsid'],
//                'express_company'   =>$data['delivery_id'],
            'cptitle' => '购买产品',
            'jjrtel' => config('tel'),
            'sjrtel' => $sjrxx['tel'],
            'openid' => $openid,
        ];
    } else {
        $arr = [
            'ordersn' => $post['ordersn'],
            'type' => 1,
            'tracking_no' => $post['emsid'],
            'express_company' => $post['delivery_id'],
            'cptitle' => '购买产品',
            'jjrtel' => maskPhone(config('tel')),
            'sjrtel' => maskPhone($sjrxx['tel']),
            'openid' => $openid,
        ];
    }


    $data = [
        'order_key' => [
            'order_number_type' => 1,
//                'transaction_id' => $result['transaction_id'],
            'mchid' => $result['mch_id'],
            'out_trade_no' => $arr['ordersn'] . 'ab'
        ],
        'logistics_type' => intval($arr['type']), //1/物流，4/自提
        'delivery_mode' => 1,
        'shipping_list' => [[
            'tracking_no' => $arr['tracking_no'],
            'express_company' => $post['delivery_id'],
            'item_desc' => $arr['cptitle'],
            'contact' => [
                'consignor_contact' => $arr['jjrtel'],
                'receiver_contact' => $arr['sjrtel']
            ],
        ]],
        'upload_time' => $rfc3339Time,
        'payer' => [
            'openid' => $arr['openid']
        ]
    ];

    $postUrl = sprintf("https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=%s", $token);

    // 将数组转化为JSON格式
    $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
    // 发起POST请求
    $result = string2array(curlPost($postUrl, $jsonData));

    return $result;


}


/**
 * 将字符串转换为数组
 *
 * @param string $data 字符串
 * @return   array   返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data)
{
//    $data = trim($data);
    if ($data == '') return array();
    if (strpos($data, 'array') === 0) {
        @eval("\$array = $data;");
    } else {
        if (strpos($data, '{\\') === 0) $data = stripslashes($data);
        $array = json_decode(htmlspecialchars_decode($data), true);
    }
    return $array;
}


function curlPost($url = '', $postData = '', $options = array())
{
    if (is_array($postData)) {
        $postData = http_build_query($postData);
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    //https请求 不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}


/**
 * 微信确认收货
 */
function WxSendqrshOrder($post, $token)
{
    $config = [
        'app_id' => config('appid'),
        'mch_id' => config('mch_id'),
        'key' => config('paySecret'),
        'cert_path' => '', // XXX: 绝对路径！！！！
        'key_path' => '',      // XXX: 绝对路径！！！！
        'notify_url' => conf("lm", "url") . 'payres',
    ];

    $app = Factory::payment($config);

    $result = $app->order->queryByOutTradeNumber($post['ordersn']);

//    dump($result['transaction_id']);die;

    $str = "购买产品";

    $str_utf8 = mb_convert_encoding($str, "UTF-8", "auto");


    $data = [
        'transaction_id' => $result['transaction_id'],
        'merchant_id' => $result['mch_id'],
        'received_time' => time()
    ];
    $postUrl = sprintf("https://api.weixin.qq.com/wxa/sec/order/notify_confirm_receive?access_token=%s", $token);

    // 将数组转化为JSON格式
    $jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
    // 发起POST请求
    $result = string2array(curlPost($postUrl, $jsonData));
    return $result;
}

//输入用户id获取用户的服务中心 分公司 董事
function getUpperLevelIds($user_id)
{
    $result = [
        'service_center_id' => 0,
        'branch_id' => 0,
        'director_id' => 0,
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找
    $current_user = Db::name('user')
        ->where('id', $user_id)
        ->field('invite_id')
        ->find();

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找

    // 最多查询100层，防止死循环
    $max_level = 100;
    $current_level = 0;

    while ($current_id != 0 && $current_level < $max_level) {
        $current_level++;

        // 查询当前用户的信息
        $user = Db::name('user')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();

        if (!$user) {
            break; // 用户不存在，终止
        }

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center_id'])) {
                    $result['service_center_id'] = $user['id'];
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch_id'])) {
                    $result['branch_id'] = $user['id'];
                }
                break;
            case 6: // 董事
                if (is_null($result['director_id'])) {
                    $result['director_id'] = $user['id'];
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center_id']) &&
            !is_null($result['branch_id']) &&
            !is_null($result['director_id'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
    }

    return $result;
}

//显示每个角色的层级关系 测试
function getUpperLevelIds2($user_id)
{
    $result = [
        'hierarchy' => [],            // 记录查找顺序
        'service_center_id' => null,   // 服务中心ID
        'branch_id' => null,          // 分公司ID
        'director_id' => null,        // 董事ID
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找（不包含自己）
    $current_user = Db::name('member')
        ->where('id', $user_id)
        ->field('invite_id')
        ->find();

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找
    $current_level = 1; // 层级计数（从1开始）

    // 最多查询100层，防止死循环
    $max_level = 100;

    while ($current_id != 0 && $current_level <= $max_level) {
        // 查询当前用户的信息
        $user = Db::name('member')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();


        if (!$user) {
            break; // 用户不存在，终止
        }

        // 记录当前层级信息
        $result['hierarchy'][] = [
            'level' => $current_level,
            'user_id' => $user['id'],
            'user_level' => $user['level_id'],
        ];

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center_id'])) {
                    $result['service_center_id'] = $user['id'];
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch_id'])) {
                    $result['branch_id'] = $user['id'];
                }
                break;
            case 6: // 董事
                if (is_null($result['director_id'])) {
                    $result['director_id'] = $user['id'];
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center_id']) &&
            !is_null($result['branch_id']) &&
            !is_null($result['director_id'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
        $current_level++;
    }

    return $result;
}

function getUpperLevelIds3($user_id)
{
    $result = [
        'member' => null,
        'service_center' => null,   // 服务中心ID
        'branch' => null,          // 分公司ID
        'director' => null,        // 董事ID
    ];

    // 先获取当前用户的 invite_id，直接从上一层开始找（不包含自己）
    $current_user = Db::name('member')
        ->where('id', $user_id)
        ->field('invite_id,id,level_id')
        ->find();
    $result['member']['member_id'] = $current_user['id'];
    $result['member']['level_id'] = $current_user['level_id'];

    if (!$current_user || $current_user['invite_id'] == 0) {
        return $result; // 没有邀请人，直接返回空
    }

    $current_id = $current_user['invite_id']; // 从邀请人开始找
    $current_level = 1; // 层级计数（从1开始）

    // 最多查询100层，防止死循环
    $max_level = 100000;

    while ($current_id != 0 && $current_level <= $max_level) {
        // 查询当前用户的信息
        $user = Db::name('member')
            ->where('id', $current_id)
            ->field('id, invite_id, level_id')
            ->find();

        if (!$user) {
            break; // 用户不存在，终止
        }

        // 检查 level_id 并记录
        switch ($user['level_id']) {
            case 4: // 服务中心
                if (is_null($result['service_center'])) {
                    $result['service_center']['member_id'] = $user['id'];
                    $result['service_center']['level_id'] = $user['level_id'];
                    $result['service_center']['top'] = $current_level;
                }
                break;
            case 5: // 分公司
                if (is_null($result['branch'])) {
                    $result['branch']['member_id'] = $user['id'];
                    $result['branch']['level_id'] = $user['level_id'];
                    $result['branch']['top'] = $current_level;
                }
                break;
            case 6: // 董事
                if (is_null($result['director'])) {
                    $result['director']['member_id'] = $user['id'];
                    $result['director']['level_id'] = $user['level_id'];
                    $result['director']['top'] = $current_level;
                }
                break;
        }

        // 如果已经找到所有目标，提前终止
        if (
            !is_null($result['service_center']) &&
            !is_null($result['branch']) &&
            !is_null($result['director'])
        ) {
            break;
        }

        // 继续向上查找
        $current_id = $user['invite_id'];
        $current_level++;
    }

    return $result;
}
function reBuyReward2($order_id,$member_id)
{
    $order_info = Db::name('order')->find($order_id);
    if (!$order_info) {
        return 0;
    }
    $member_info=Db::name('member')->find($member_id);
    //用户是董事不用返现
    //1普通会员 2代理 3老板 4服务中心 5分公司 6董事
    if ($member_info['level_id'] >= 6) {
        return 0;
    }

    $return_data = getUpperLevelIds3($member_info['id']);
    if (!is_null($return_data['service_center'])) {
        if ($member_info['level_id'] >= $return_data['service_center']['level_id']) {
            $return_data['service_center'] = null;
        }
    }
    if (!is_null($return_data['branch'])) {
        if ($member_info['level_id'] >= $return_data['branch']['level_id']) {
            $return_data['branch'] = null;
        }
        if ($return_data['branch']['top'] == 1) {
            $return_data['service_center'] = null;
        }
    }
    if (!is_null($return_data['director'])) {
        if ($member_info['level_id'] >= $return_data['director']['level_id']) {
            $return_data['director'] = null;
        }
        if ($return_data['director']['top'] == 1) {
            $return_data['service_center'] = null;
            $return_data['branch'] = null;
        }
        if ($return_data['director']['top'] == 2) {
            if (!is_null($return_data['service_center'])) {
                if ($return_data['service_center']['top'] == 3) {
                    $return_data['service_center'] = null;
                }
            }
            if (!is_null($return_data['branch'])) {
                if ($return_data['branch']['top'] == 3) {
                    $return_data['branch'] = null;
                }
            }
        }
    }
    msg(0,'查询成功',$return_data);
    //获取订单商品
    $order_goods = Db::name('order_goods')->where([
        ['order_id', '=', $order_id]
    ])->select();
    foreach ($order_goods as $k => $v) {
        if (!is_null($return_data['service_center'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 4],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money'];
                reward($return_data['service_center']['member_id'], $order_info, $money, 6, $order_info['member_id'], $v, 1, '复购奖励');
            }
        }
        if (!is_null($return_data['branch'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 5],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money'];
                if (is_null($return_data['service_center'])) {
                    $goods_fg_fx2 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 4],
                    ])->find();
                    if ($goods_fg_fx2){
                        $money+=$goods_fg_fx2['money'];
                    }
                }
                reward($return_data['service_center']['member_id'], $order_info, $money, 7, $order_info['member_id'], $v, 1, '复购奖励');
            }
        }
        if (!is_null($return_data['director'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 6],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money'];
                if (is_null($return_data['service_center'])) {
                    $goods_fg_fx2 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 4],
                    ])->find();
                    if ($goods_fg_fx2){
                        $money+=$goods_fg_fx2['money'];
                    }
                }
                if (is_null($return_data['branch'])) {
                    $goods_fg_fx3 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 5],
                    ])->find();
                    if ($goods_fg_fx3){
                        $money+=$goods_fg_fx3['money'];
                    }
                }
                reward($return_data['service_center']['member_id'], $order_info, $money, 8, $order_info['member_id'], $v, 1, '复购奖励');
            }
        }
    }
}

//发放复购奖励
function reBuyReward($order_info)
{
    $order_id=$order_info['id'];
    $member_info=Db::name('member')->find($order_info['member_id']);
    //用户是董事不用返现
    //1普通会员 2代理 3老板 4服务中心 5分公司 6董事
    if ($member_info['level_id'] >= 6) {
        return 0;
    }

    $return_data = getUpperLevelIds3($member_info['id']);
    if (!is_null($return_data['service_center'])) {
        if ($member_info['level_id'] >= $return_data['service_center']['level_id']) {
            $return_data['service_center'] = null;
        }
    }
    if (!is_null($return_data['branch'])) {
        if ($member_info['level_id'] >= $return_data['branch']['level_id']) {
            $return_data['branch'] = null;
        }
        if ($return_data['branch']['top'] == 1) {
            $return_data['service_center'] = null;
        }
    }
    if (!is_null($return_data['director'])) {
        if ($member_info['level_id'] >= $return_data['director']['level_id']) {
            $return_data['director'] = null;
        }
        if ($return_data['director']['top'] == 1) {
            $return_data['service_center'] = null;
            $return_data['branch'] = null;
        }
        if ($return_data['director']['top'] == 2) {
            if (!is_null($return_data['service_center'])) {
                if ($return_data['service_center']['top'] == 3) {
                    $return_data['service_center'] = null;
                }
            }
            if (!is_null($return_data['branch'])) {
                if ($return_data['branch']['top'] == 3) {
                    $return_data['branch'] = null;
                }
            }
        }
    }
    //获取订单商品
    $order_goods = Db::name('order_goods')->where([
        ['order_id', '=', $order_id]
    ])->select();

    foreach ($order_goods as $k => $v) {
        if (!is_null($return_data['service_center'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 4],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money']*$v['num'];
                reward($return_data['service_center']['member_id'], $order_info, $money, 10, $order_info['member_id'], $v, 1, '服务中心复购奖励');
            }
        }
        if (!is_null($return_data['branch'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 5],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money']*$v['num'];;
                if (is_null($return_data['service_center'])) {
                    $goods_fg_fx2 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 4],
                    ])->find();
                    if ($goods_fg_fx2){
                        $money+=($goods_fg_fx2['money']*$v['num']);
                    }
                }
                reward($return_data['branch']['member_id'], $order_info, $money, 11, $order_info['member_id'], $v, 1, '分公司复购奖励');
            }
        }
        if (!is_null($return_data['director'])) {
            $goods_fg_fx = Db::name('goods_fg_fx')->where([
                ['goods_id', '=', $v['goods_id']],
                ['level_id', '=', 6],
            ])->find();
            if ($goods_fg_fx) {
                $money = $goods_fg_fx['money']*$v['num'];
                if (is_null($return_data['service_center'])) {
                    $goods_fg_fx2 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 4],
                    ])->find();
                    if ($goods_fg_fx2){
                        $money+=($goods_fg_fx2['money']*$v['num']);
                    }
                }
                if (is_null($return_data['branch'])) {
                    $goods_fg_fx3 = Db::name('goods_fg_fx')->where([
                        ['goods_id', '=', $v['goods_id']],
                        ['level_id', '=', 5],
                    ])->find();
                    if ($goods_fg_fx3){
                        $money+=($goods_fg_fx3['money']*$v['num']);
                    }
                }
                reward($return_data['director']['member_id'], $order_info, $money, 12, $order_info['member_id'], $v, 1, '董事复购奖励');
            }
        }
    }
}

//升级服务中心
function upServerCenter($order_info){
    $linkage_info = Db::name('linkage')->find();
    $order_goods = Db::name('order_goods')->where([
        'order_id' => $order_info['id'],
        'goods_id' => $linkage_info['goods_id']
    ])->find();
    //判断商品数量
    if ($order_goods['num']>=100){
       $member_info=Db::name('member')->find($order_info['member_id']);
       if ($member_info['level_id']<4){
           Db::name('member')->update([
               'id'=>$order_info['member_id'],
               'level_id'=>4
           ]);
       }
    }
}

//升级分公司
function upBrand($order_info){
    $member=Db::name('member')->find($order_info['member_id']);
    $up_member=Db::name('member')->find($member['invite_id']);
    $junior_count=Db::name('member')->where([
        ['invite_id','=',$up_member['id']],
        ['level_id','=',4],
        ['id','not in',[$up_member['one_id'],$up_member['tow_id']]]
    ])->count();
    if ($up_member['level_id']==4&&$junior_count>=7){
        Db::name('member')->update([
            'id'=>$up_member['id'],
            'level_id'=>5
        ]);
    }
}
//todo









